from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm

from app.models import user_data
from app.utils.jwt_service import gen_jwt
from app.business.user import is_user_exist
from app.api.response import Response
from app.api.status import Status

default_router = APIRouter()


@default_router.get("/ping", summary="ping")
def ping():
    return "pong"


# token
@default_router.post("/token", summary="token")
def token(form_data: OAuth2PasswordRequestForm = Depends()):
    if not is_user_exist(form_data.username):
        return Response.failure(msg="用户不存在", status=Status.USER_NOT_EXIST)
    data = [i for i in user_data if i.get("account") == form_data.username][0]
    access_token = gen_jwt(data)
    return {"access_token": access_token, "token_type": "bearer"}
